<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 */

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Log;
use think\Request;
use think\Config;

class Auth extends Common {

	//规则列表
	public function auth_list(){
		return $this->fetch();
	}

	//添加规则
	public function auth_add(){
		if (Request::instance()->isPost()) {
			$post = $_POST;
			if (empty($post['title'])) {
				echo json_encode(array('error' => 1,'msg'=>'请填写规则名称'));exit; 
			}
			if (empty($post['path'])) {
				echo json_encode(array('error' => 1,'msg'=>'请填写规则路径'));exit; 
			}
			if (empty($post['status'])) {
				echo json_encode(array('error' => 1,'msg'=>'请填写规则状态'));exit; 
			}
			$data = array(
				'title' => preg_replace('# #','',$post['title']),
				'path' => preg_replace('# #','',$post['path']),
				'status' => preg_replace('# #','',$post['status']) != 1?2:1
			);
			$result = Db::table('admin_auth_rule')->insertGetId($data);
			if ($result) {
				//记录log日志
             	$this->action_log('添加了权限规则，ID#'.serialize($data));
				echo json_encode(array('error' => 0,'msg' => '添加成功'));exit;
			}else{
				echo json_encode(array('error' => 1,'msg' => '添加失败'));exit;
			}
			
		}
		return $this->fetch();
	}

	//角色分组列表
	public function group_list(){
		$groups = Db::table('admin_auth_group')->select();
		$this->assign(['groups' => $groups]);
		return $this->fetch();
	}

	//添加角色分组
	public function group_add(){
		if (Request::instance()->isPost()) {
			$post = $_POST;
			if (empty($post['group_name'])) {
				echo json_encode(array('error' => 1,'msg' => '请填写角色名称'));exit;
			}
			if (Db::table('admin_auth_group')->where(array('group_name' => $post['group_name']))->count() > 0) {
				echo json_encode(array('error' => 1,'msg' => '角色名称已存在'));exit; 
			}
			if (empty($post['menus'])) {
				echo json_encode(array('error' => 1,'msg' => '请选择至少一个首页菜单'));exit;
			}
			if (empty($post['status'])) {
				$post['status'] = 1;
			}
			$data = array(
				'group_name' => $post['group_name'],
				'menus' => implode(',',$post['menus']),
				'status' => $post['status']
			);
			$result = Db::table('admin_auth_group')->insertGetId($data);
			if ($result) {
				//记录log日志
             	$this->action_log('添加了角色分组，ID#'.serialize($data));
				echo json_encode(array('error' => 0,'msg' => '添加角色成功'));exit;
			}else{
				echo json_encode(array('error' => 1,'msg' => '添加角色失败'));exit;
			}
		}
		//获取所有菜单
        $menus = Db::table('admin_menu')->where('status=1 and menu_url != ""')->order('pid ASC,seq DESC')->select();
        $this->assign(['menus' => $menus]);
		return $this->fetch();
	}

	//编辑角色分组
	public function group_edit(){
		if (Request::instance()->isPost()) {
			$post = $_POST;
			if (empty($post['auth_group_id'])) {
				echo json_encode(array('error' => 1,'msg' => '参数错误'));exit;
			}
			if (empty($post['group_name'])) {
				echo json_encode(array('error' => 1,'msg' => '请填写角色名称'));exit;
			}
			if (Db::table('admin_auth_group')->where(array('group_name' => $post['group_name'],'auth_group_id' => array('neq',$post['auth_group_id'])))->count() > 0) {
				echo json_encode(array('error' => 1,'msg' => '角色名称已存在'));exit; 
			}
			if (empty($post['menus'])) {
				echo json_encode(array('error' => 1,'msg' => '请选择至少一个首页菜单'));exit;
			}
			if (empty($post['status'])) {
				$post['status'] = 1;
			}
			$data = array(
				'group_name' => $post['group_name'],
				'menus' => implode(',',$post['menus']),
				'status' => $post['status']
			);
			$result = Db::table('admin_auth_group')->where(array('auth_group_id'=>$post['auth_group_id']))->update($data);
			if (is_int($result)) {
				//记录log日志
             	$this->action_log('修改了角色分组ID'.$post['auth_group_id'].'，为#'.serialize($data));
				echo json_encode(array('error' => 0,'msg' => '修改角色成功'));exit;
			}else{
				echo json_encode(array('error' => 1,'msg' => '修改角色失败'));exit;
			}
		}
		if (empty($_GET['auth_group_id'])) {
			echo '<script>swal("参数错误", "", "success");setTimeout("self.location=document.referrer;",2000);</script>';exit;
		}
		//获取角色信息
		$group_res = Db::table('admin_auth_group')->where(array('auth_group_id'=>$_GET['auth_group_id']))->find();
		//获取所有菜单
        $menus = Db::table('admin_menu')->where('status=1 and menu_url != ""')->order('pid ASC,seq DESC')->select();

        $this->assign(['group_res' => $group_res,'menus' => $menus]);
		return $this->fetch();
	}

	//删除角色分组
	public function group_del(){
		if (Request::instance()->isPost()) {
			$post = $_POST;
			if (empty($post['auth_group_id'])) {
				echo json_encode(array('error' => 1,'msg' => '参数错误'));exit;
			}
			$result = Db::table('admin_auth_group')->where(array('auth_group_id'=>$post['auth_group_id']))->delete();
			if ($result) {
				//记录log日志
             	$this->action_log('删除了角色分组，ID#'.$post['auth_group_id']);
				echo json_encode(array('error' => 0,'msg' => '删除角色成功'));exit;
			}else{
				echo json_encode(array('error' => 1,'msg' => '删除角色失败'));exit;
			}
		}
	}

	//修改角色分组状态
	public function group_status(){
		if (Request::instance()->isPost()) {
			$post = $_POST;
			if (empty($post['status']) || empty($post['auth_group_id'])) {
				echo json_encode(array('error' => 1,'msg' => '参数错误'));exit; 
			}
			$where = array(
				'auth_group_id' => $post['auth_group_id']
			);
			if ($post['status'] == 1) {
				$str = '启用';
			}else{
				$str = '禁用';
			}
			$result = Db::table('admin_auth_group')->where($where)->setField('status',$post['status']);
			if ($result) {
				//记录log日志
             	$this->action_log('修改了角色分组ID'.$post['auth_group_id'].'状态，为#'.$post['status']);
				echo json_encode(array('error' => 0,'msg' => $str.'成功'));exit;
			}else{
				echo json_encode(array('error' => 1,'msg' => $str.'失败'));exit;
			}
			
		}
	}

	//管理员列表
	public function admin_list(){
		$admins = Db::table('admin a,admin_auth_group aag')->field('a.*,aag.group_name')->where('a.auth_group_id=aag.auth_group_id')->select();
		$this->assign(['admins' => $admins]);
		return $this->fetch();
	}

	//添加管理员
	public function admin_add(){
		if (Request::instance()->isPost()) {
			$post = $_POST;
			if (empty($post['username'])) {
				echo json_encode(array('error' => 1,'msg'=>'请填写管理员帐号'));exit; 
			}
			if (Db::table('admin')->where(array('username' => $post['username']))->count() > 0) {
				echo json_encode(array('error' => 1,'msg' => '管理员帐号已存在'));exit; 
			}
			if (empty($post['password'])) {
				echo json_encode(array('error' => 1,'msg'=>'请填写管理员密码'));exit; 
			}
			if (empty($post['auth_group_id'])) {
				echo json_encode(array('error' => 1,'msg'=>'请选择管理员角色'));exit; 
			}
			if (empty($post['status'])) {
				echo json_encode(array('error' => 1,'msg'=>'请选择菜单状态'));exit; 
			}

			$data = array(
				'username' => preg_replace('# #','',$post['username']),
				'password' => md5(preg_replace('# #','',$post['password'])),
				'auth_group_id' => preg_replace('# #','',$post['auth_group_id']),
				'status' => preg_replace('# #','',$post['status']) != 1?2:1,
			);
			$result = Db::table('admin')->insertGetId($data);
			if ($result) {
				//记录log日志
             	$this->action_log('添加了管理员，ID#'.$result);
				echo json_encode(array('error' => 0,'msg' => '添加成功'));exit;
			}else{
				echo json_encode(array('error' => 1,'msg' => '添加失败'));exit;
			}
		}
		$groups = Db::table('admin_auth_group')->where('auth_group_id != 1')->select();
		$this->assign(['groups' => $groups]);
		return $this->fetch();
	}

	//修改管理员
	public function admin_edit(){
		if (Request::instance()->isPost()) {
			$post = $_POST;
			if (empty($post['id'])) {
				echo json_encode(array('error' => 1,'msg' => '参数错误'));exit; 
			}
			if (empty($post['username'])) {
				echo json_encode(array('error' => 1,'msg' => '请填写管理员帐号'));exit; 
			}
			if (Db::table('admin')->where(array('username' => $post['username'],'id' => array('neq',$post['id'])))->count() > 0) {
				echo json_encode(array('error' => 1,'msg' => '管理员帐号已存在'));exit; 
			}
			if (empty($post['auth_group_id'])) {
				echo json_encode(array('error' => 1,'msg' => '请选择管理员角色'));exit; 
			}

			$data = array(
				'username' => preg_replace('# #','',$post['username']),
				'auth_group_id' => preg_replace('# #','',$post['auth_group_id']),
			);
			if (!empty($post['password'])) {
				$data['password'] = md5(preg_replace('# #','',$post['password']));
			}
			$result = Db::table('admin')->where(array('id' => $post['id']))->update($data);
			if (is_int($result)) {
				//记录log日志
             	$this->action_log('修改了管理员ID'.$post['id'].'为#'.serialize($data));
				echo json_encode(array('error' => 0,'msg' => '修改成功'));exit;
			}else{
				echo json_encode(array('error' => 1,'msg' => '修改失败'));exit;
			}
		}
		if (empty($_GET['id'])) {
			echo '<script>swal("参数错误", "", "success");setTimeout("self.location=document.referrer;",2000);</script>';exit;
		}
		$groups = Db::table('admin_auth_group')->where('auth_group_id != 1')->select();
		$admin = Db::table('admin')->find($_GET['id']);
		$this->assign(['groups' => $groups,'admin' => $admin]);
		return $this->fetch();
	}


	//修改管理员状态
	public function admin_status(){
		if (Request::instance()->isPost()) {
			$post = $_POST;
			if (empty($post['status']) || empty($post['id'])) {
				echo json_encode(array('error' => 1,'msg' => '参数错误'));exit; 
			}
			$where = array(
				'id' => $post['id']
			);
			if ($post['status'] == 1) {
				$str = '启用';
			}else{
				$str = '禁用';
			}
			
			$result = Db::table('admin')->where($where)->setField('status',$post['status']);
			if ($result) {
				//记录log日志
             	$this->action_log('修改了管理员'.$post['id'].'状态为#'.$post['status']);
				echo json_encode(array('error' => 0,'msg' => $str.'成功'));exit;
			}else{
				echo json_encode(array('error' => 1,'msg' => $str.'失败'));exit;
			}
			
		}
	}

	//修改密码
	public function password_edit(){
		$admin = session('admin');

		if (Request::instance()->isPost()) {
			$post = $_POST;
			if (empty($admin['id'])) {
				echo json_encode(array('error' => 1,'msg' => '参数错误'));exit;
			}
			if (empty($post['old_password'])) {
				echo json_encode(array('error' => 1,'msg' => '请输入原密码'));exit;
			}
			if (empty($post['password'])) {
				echo json_encode(array('error' => 1,'msg' => '请输入新密码'));exit;
			}
			if (empty($post['confirm_password'])) {
				echo json_encode(array('error' => 1,'msg' => '请输入确认密码'));exit;
			}
			if ($post['password'] != $post['confirm_password']) {
				echo json_encode(array('error' => 1,'msg' => '两次密码不一致'));exit;
			}
			if ( Db::table('admin')->where(array('id' => $admin['id'], 'password' => md5($post['old_password'])))->count() <= 0) {
				echo json_encode(array('error' => 1,'msg' => '原密码输入错误'));exit;	
			}
			$result = Db::table('admin')->where(array('id' => $admin['id']))->setField('password',md5($post['password']));
			if ($result) {
				//记录log日志
             	$this->action_log('修改了管理员密码');
				echo json_encode(array('error' => 0,'msg' => '修改成功，即将退出重新登录'));exit;
			}else{
				echo json_encode(array('error' => 1,'msg' => '修改失败'));exit;
			}
		}
		$this->assign(['admin' => $admin]);
		return $this->fetch();
	}

	//操作日志
    public function action_log_list()
    {
        $table = Db::table('admin_action_log');

        $where = ['admin_id' => $_SESSION['admin']['id']];
        $step = 10;
        $count = $table->where($where)->count();

        $page = new \Think\Page($count,$step);
        $res = $table->where($where)->order('log_time desc')->limit($page->firstRow,$step)->select();

        $this->assign(['res' => $res,'page' => array('page' => $page->show(),'firstRow' => $page->firstRow)]);
        return $this->fetch();
    }

}


